<template>
  <a-form layout="inline" class="timeRange">
    <a-form-item :label="$t('common.time')">
      <a-select v-model:value="timer" style="width: 150px">
        <a-select-option
          v-for="option in timeList"
          :key="option.value"
          :value="option.value"
        >
          {{ option.label }}
        </a-select-option>
      </a-select>
      <a-range-picker
        v-if="!timer"
        v-model:value="timeRange"
        :showTime="true"
        format="YYYY-MM-DD HH:mm:ss"
        :disabled-date="disabledDate"
        @change="changeClick"
      />
    </a-form-item>
    <a-form-item :label="$t('common.period')" v-if="hadPeriod">
      <a-select v-model="period" :popper-append-to-body="false" style="width: 100px" @change="isChange = false">
        <a-select-option
          v-for="option in periodList"
          :key="option.value"
          :value="option.value"
        >
          {{ option.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
  </a-form>
</template>

<script setup>
import i18n from '@/locales/index'
import {computed, onMounted, watch, ref, nextTick} from "vue";
import dayjs from "dayjs";
const { t } = i18n.global

const ONE_SECOND = 1
const ONE_MINUTE = 60 * ONE_SECOND
const ONE_HOUR = 60 * ONE_MINUTE
const ONE_DAY = ONE_HOUR * 24

const periodDict = {
  halfMin: {
    label: t('common.second', ['30']),
    value: ONE_SECOND * 30,
  },
  oneMin: {
    label: t('common.minute', ['1']),
    value: ONE_MINUTE,
  },
  fiveMin: {
    label: t('common.minute', ['5']),
    value: ONE_MINUTE * 5,
  },
  fifteenMin: {
    label: t('common.minute', ['15']),
    value: ONE_MINUTE * 15,
  },
  halfHour: {
    label: t('common.minute', ['30']),
    value: ONE_MINUTE * 30,
  },
  oneHour: {
    label: t('common.hour', ['1']),
    value: ONE_HOUR,
  },
  threeHour: {
    label: t('common.hour', ['3']),
    value: ONE_HOUR * 3,
  },
}

const timeList = [
  {
    label: t('common.costomTime'),
    value: '',
  },
  {
    label: t('common.hourLabel', ['1']),
    value: ONE_HOUR,
  },
  {
    label: t('common.hourLabel', ['6']),
    value: ONE_HOUR * 6,
  },
  {
    label: t('common.hourLabel', ['12']),
    value: ONE_HOUR * 12,
  },
  {
    label: t('common.dayLabel', ['1']),
    value: ONE_DAY,
  },
  {
    label: t('common.dayLabel', ['3']),
    value: ONE_DAY * 3,
  },
]

function changeOption(timeLen) {
  if (timeLen <= ONE_HOUR) {
    return [periodDict.halfMin, periodDict.oneMin, periodDict.fiveMin]
  }
  if (timeLen < ONE_HOUR * 6) {
    return [periodDict.oneMin, periodDict.fiveMin, periodDict.fifteenMin, periodDict.halfHour, periodDict.oneHour]
  }
  if (timeLen < ONE_DAY) {
    return [periodDict.fiveMin, periodDict.fifteenMin, periodDict.halfHour, periodDict.oneHour]
  }
  if (timeLen < ONE_DAY * 3) {
    return [periodDict.fifteenMin, periodDict.halfHour, periodDict.oneHour]
  }
  return [periodDict.halfHour, periodDict.oneHour, periodDict.threeHour]
}

const emits = defineEmits(['changeTime'])
const props = defineProps({
  id: {
    // id用于初始化
    type: String,
    default: '',
  },
  initTimer: {
    // initTimer为初始化时间，没有则初始化为当前时间
    type: Object,
    default: null,
  },
  refresh: {
    // 变化则刷新时间
    type: Boolean,
  },
  hadPeriod: {
    // 是否有周期下拉框
    type: Boolean,
    default: true,
  },
})

const isChange = ref(false); // 用于监听是否已经触发更改
const timer = ref(ONE_HOUR);
const timeRange = ref([]);
const period = ref(ONE_SECOND * 30);
const periodList = ref([periodDict.halfMin, periodDict.oneMin, periodDict.fiveMin]);


function disabledDate(current) {
  const minValue = dayjs().subtract(3, 'days')
  return current.isBefore(minValue) || current.isAfter(dayjs())
}
function changeTime() {
  let start = dayjs().subtract(timeLen.value, 'seconds')
  let end = dayjs()
  if (!timer.value) {
    // 自定义
    start = timeRange.value[0]
    end = timeRange.value[1]
  }
  isChange.value = true
  emits('changeTime', start.valueOf(), end.valueOf(), period.value, timer.value)
}

function changeClick(val) {
  console.log(val)
}

const timeLen = computed(() => {
  if (!timer.value && timeRange.value[1]) {
    return (timeRange.value[1].valueOf() - timeRange.value[0].valueOf()) / 1000
  }
  return timer.value
})

watch(() => props.refresh, (val) => {
  if (val) {
    isChange.value = false
  }
},{ immediate: true })

watch(() => timer.value, (val, old) => {
  if (!val) {
    timeRange.value = [dayjs().subtract(old, 'seconds'), dayjs()]
    return
  }
  isChange.value = false
},{ immediate: true })

watch(() => timeRange.value, (val) => {
  if (val === null) {
    timeRange.value = [dayjs().subtract(1, 'hours'), dayjs()]
  }
  isChange.value = false
},{ immediate: true })

watch(() => timeLen.value, (val) => {
  periodList.value = changeOption(val)
  period.value = periodList.value[0].value
},{ immediate: true })

watch(() => props.id, (val) => {
  if (!val) {
    return
  }

  // 切换后初始化时间
  timer.value = ONE_HOUR
  timeRange.value = []
  period.value = ONE_SECOND * 30
  isChange.value = false
},{ immediate: true })

watch(() => isChange.value, (val) => {
  if (!val) {
    changeTime()
  }
},{ immediate: true })


onMounted(() => {
  if (props.initTimer && props.initTimer.period) {
    timer.value = props.initTimer.timer
    period.value = props.initTimer.period
    if (!timer.value) {
      timeRange.value = [dayjs(props.initTimer.start), dayjs(props.initTimer.end)]
    }
  }
  nextTick(() => {
    changeTime()
  })
})

</script>

<style scoped lang="less">
::v-deep {
  .el-range-editor--small .el-range-separator {
    color: rgb(219, 210, 210);
  }
  .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 0px;
  }
  .el-input {
    width: 100%;
  }
}
</style>
